﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FHost1
{
    /// <summary>
    /// Summary description for DownloadHandler
    /// </summary>
    public class DownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString.AllKeys.Contains("id"))
            {
                context.Response.ContentType = "text/plain";
                int fileId = Convert.ToInt32(context.Request.QueryString["id"]);
                using (FHostDataContext dataContext = new FHostDataContext())
                {
                    List<FileUpload> fileUploads = dataContext.FileUploads.Where(obj => (obj.FileID == fileId)).ToList();
                    if (fileUploads.Count > 0)
                    {
                        context.Response.ContentType = fileUploads[0].FileExt;
                        context.Response.BinaryWrite(fileUploads[0].FileData.ToArray());
                    }
                    else
                    {
                        context.Response.Write("File does not exists!");
                    }
                }

            }
            else
            {
                context.Response.Write("File does not exists!");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}